package org.elephas.webapp.application;

import org.apache.wicket.Page;
import org.apache.wicket.Response;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.WebRequestCycle;
import org.elephas.service.BlogNotFoundException;
import org.elephas.service.PostNotFoundException;
import org.elephas.webapp.frontend.page.error.NotFoundPage;

public class ElephasRequestCycle extends WebRequestCycle {

	public ElephasRequestCycle(WebApplication application, WebRequest request,
			Response response) {
		super(application, request, response);
	}

	@Override
	public Page onRuntimeException(Page page, RuntimeException e) {
		Throwable t = getCause(e, BlogNotFoundException.class);
		if (t != null) {
			// TODO: return something like BlogNotFoundPage
			return new NotFoundPage();
		}
		t = getCause(e, PostNotFoundException.class);
		if (t != null) {
			// TODO: return something like PostNotFoundPage
			return new NotFoundPage();
		}
		return super.onRuntimeException(page, e);
	}

	private Throwable getCause(RuntimeException e,
			Class<? extends Throwable> targetCause) {
		Throwable cursor = e;
		while (cursor != null
				&& !targetCause.isAssignableFrom(cursor.getClass())) {
			cursor = cursor.getCause();
		}

		return cursor;
	}

}
